#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import os
	import pygame
	import sys
	from pygame.font import Font, SysFont
	import pygame.surfarray
	import numpy as N
	from pygame.locals import *

except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)


def load_image(name):
	fullname = os.path.join(name)
	try:
		surface = pygame.image.load(fullname)
	except pygame.error, message:
		print 'Cannot load image:', name
		raise SystemExit, message
	return surface.convert()


MenuBackgroundColor = (0, 0, 128)
WHITE = (255, 255, 255)
BLACK = (0,0,0)

FLD_TILE_SZ = 48

ERWIN_3 = 'img0189a'
WINDOW = 'IMG0001B'
CURSOR_ICONS = 'BC2b'

DIR_UP = 0
DIR_DOWN = 1
DIR_RIGHT = 2
DIR_LEFT = 3
MOVED = 4


surfaces = {}
fonts = {}

class UnitImageCache(object):
	"""
	Unit Cache.

	Stores all the possible Unit Images in itself and calls/creates each one
	on get()
	"""
	def __init__(self):
		self.cache = {}

	def get(self, creature):
		"""
		Returns the UnitImageCacheObject or creates it
		"""
		if not creature in surfaces or surfaces[creature] is None:
			self.cache[creature] = UnitImageCacheObject(creature)
		return self.cache[creature]



class UnitImageCacheObject(object):
	"""
	Unit cache object.

	Loads image on creation. Calls images with get()
	"""
	def __init__(self, creature):

		#Loads base sprite
		sprite = load_image('./data/spr/' + creature + '.pcx')

		#Loads sprites into list - list[Direction][Animation]
		self.sprite = []
		self.sprite.append([sprite.subsurface(((64 * 2, 64), (48, 48))),\
		sprite.subsurface(((64 * 3, 64), (48, 48)))])
		self.sprite.append([sprite.subsurface(((0, 64), (48, 48))),\
		sprite.subsurface(((64, 64), (48, 48)))])
		self.sprite.append([sprite.subsurface(((0, 0), (48, 48))),\
		sprite.subsurface(((64, 0), (48, 48)))])
		self.sprite.append([pygame.transform.flip(x, True, False) for x in self.sprite[DIR_RIGHT]])
		self.sprite.append([self.desaturate(self.sprite[DIR_DOWN][0])])

		#Sets transparency for each sprite
		for dir in self.sprite:
			for s in dir:
				s.set_colorkey(s.get_at((0,0)), RLEACCEL)

	def get(self, direction, anim = 0):
		"""
		Returns specified sprite
		"""
		return self.sprite[direction][anim]

	def desaturate(self, surf):
		"""
		Desaturates the surface

		Creates a new surface and fills it with the greyscale according to the
		Gimp's Y = 0.3R + 0.59G + 0.11B

		Uses pygame.surfarray and numpy (Much faster than pixel by pixel change)

		Note: Might be efficient to just have a grayscale version in the base image itself
		"""

		rgbimg = pygame.surfarray.array3d(surf)
		rgbarray = N.array(rgbimg)

		for x, s in enumerate(rgbarray):
			for y, t in enumerate(s):
				r, g, b = t
				lum = int(0.3 * r + 0.59 * g + 0.11 * b)
				rgbarray[x][y] = [lum, lum, lum]
		return pygame.surfarray.make_surface(rgbarray).convert()

		#Pixel by pixel desaturation
#		w, h = surf.get_size()
#		desat = pygame.Surface((w, h), surf.get_flags(), surf)
#		for y in range(h):
#			for x in range(w):
#				r, g, b = surf.get_at((x, y))
#				lum = int(0.3 * r + 0.59 * g + 0.11 * b)
#				desat.set_at((x, y), (lum, lum, lum))
#		return desat


def get_window_surface():
	if not WINDOW in surfaces or surfaces[WINDOW] is None:
		surfaces[WINDOW] = load_image('./data/spr/' + WINDOW + '.pcx')
	return surfaces[WINDOW]

def get_window_font():
	if not 'window' in fonts or fonts['window'] is None:
		fonts['window'] = Font("./data/fonts/eurofurence_medium.ttf", 20)
		#fonts['window'] = SysFont("verasansyuanti", 16)
	return fonts['window']

def get_cursor_icons():
	if not CURSOR_ICONS in surfaces or surfaces[CURSOR_ICONS] is None:
		surfaces[CURSOR_ICONS] = load_image('./data/rescs/' + CURSOR_ICONS + '.pcx')
	return surfaces[CURSOR_ICONS]

